/**
  * @description: 标注&&路线地图
  * @author: hj
  * @update: hj(2020-06-08)
  */

import React, { Component } from 'react';
import styles from './index.module.scss';
import { getMediaById } from '@/service/Api/Chart';
import { observer,inject,Provider } from 'mobx-react';
import './js/map.js'; // 创建地图
import './index.css';




let map, markers = [], layerLines;

@inject('chartStore') 
@observer
class MarkerLineMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            params: [],
            data: [],
            forceFit: true, //forceFit自动试用宽度，默认false
            width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
            height: this.props.data.height ? this.props.data.height : '100%',
            condition: this.props.data.condition ? this.props.data.condition : '',
            pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
            nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
            color: this.props.data.color,
            title: '',
            chartId: this.props.data.chartId,
            id: this.props.data.componentId,
            chartData: [],
            axisArr: {},
            haveData: false,

            // 地图数据
            mapData: {
                area: '',
                data: []
            },

            dataNull: false, // 暂无数据

            // 全局变量
            mainData: [], // 操作组件可操作数据
            mainName: '', // 操作组件可操作当前维度
            mainFlag: false, // 是否是操作组件

            activeName: '', // 被选中车辆
            lines: [], // 轨迹路线
            
        };
    };


    componentWillMount() { //初始化
        const _this = this;

        console.log("markerLin")
        // 预览界面
        if (_this.state.pageFlag == 'preview') {
            // 判断当前组件是否是可操作组件
            const { globalData } = _this.props.chartStore;
            if (globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == _this.state.chartId) { // 可操作组件
                        let affectName = item.affectDimension;
                        _this.setState({
                            mainFlag: true,
                            mainName: affectName
                        })
                    }
                })
            }

            _this.interfaceRequest(_this.state.chartId,_this.state.condition);
        } else { // 配置面板
            if (_this.state.nofirst == 'nofirst') {
                _this.saveHandleData();
            } else {
                _this.interfaceRequest(_this.state.chartId,_this.state.condition);
            }
        }
    }

    // 钩子函数--组件挂载完成后
    componentDidMount() { //初始化
        this.setState({
            haveData: true
        })
    }
    // 接收父组件的数据改变
    componentWillReceiveProps = (nextProps) => {
        const _this = this;
        const { globalData, affectId } = _this.props.chartStore;

        // 预览界面---判断是否是变化组件
        if (nextProps.data.pageFlag == 'preview') {
            if (nextProps.data.condition != _this.state.requireCondition && globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == affectId && item.require == nextProps.data.chartId) { // 联动组件
                        _this.setState({
                            pageInitFlag: false
                        })
                        let condition = {};
                        Object.keys(_this.state.requireCondition).forEach(function(keys){
                            condition[keys] = keys == item.requireDimension ? nextProps.data.condition[keys] : _this.state.requireCondition[keys];
                        })
                        _this.interfaceRequest(nextProps.data.chartId,condition);
                    }
                })
            }
        }
    }

    // 数据接口请求
    interfaceRequest = (chartId,condition) => {
        const markerExtdata= window.localStorage.getItem("markerExtdata")
        if (markerExtdata){
            const markerExtdataObj=JSON.parse(markerExtdata)
            condition.order_id=markerExtdataObj.orderId
        }
        // const extData=
        this.setState({
            requireCondition: condition,
        });

        let data = {
            charId: chartId,
            condition: condition
        };
        this.getMediaById(data);
    }

    // 数据存储刷新
    saveHandleData = () => {
        const { chartArrData } = this.props.chartStore;
        if (chartArrData.slice().length > 0) {
            chartArrData.slice().map((item) => {
                if (item.id == this.state.chartId) {
                    this.setState({
                        haveData: false
                    },function() {
                        // 数据处理
                        this.handleData(item.data);
                    })
                }
            })
        }
    }


    async getMediaById(data) {
        const res = await getMediaById(data);
        if (res.data && res.data.code === 0) {
            let str = res.data;
            if (str.data && str.data.data && str.data.data.length > 0) {
                // 存储图例原始数据
                const { saveChartData } = this.props.chartStore;
                let oldData = {
                    id: this.state.chartId,
                    data: str.data.data
                }
                saveChartData(oldData);

                // 数据处理
                this.handleData(str.data.data);
            } else {
                this.setState({
                    dataNull: true
                })
            }
        } else {
            this.setState({
                dataNull: true
            })
        }
    }
    // 数据处理
    handleData = (storeAllData) => {
        let storeData = storeAllData[0];
        this.setState({
            dataNull: true
        })

        // 非预览界面
        if (this.state.pageFlag != 'preview') {
            // 存储可操作组件数据
            if (storeData.affect && storeData.affect.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveAffectData } = this.props.chartStore;

                let dimensionData = [];
                storeData.affect.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveAffectData(obj);
            }
            // 存储联动组件数据
            if (storeData.requires && storeData.requires.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveRequireData } = this.props.chartStore;

                let dimensionData = [];
                storeData.requires.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveRequireData(obj);
            }
        }

        // 页面初始化
        if (this.state.pageInitFlag) {
            if (storeData.affect &&  storeData.affect.length > 0) {
                this.setState({
                    affectName: storeData.affect[0]
                });
            }
            // 获取选择项
            if (storeData.conditionValues) {
                let selectData = storeData.conditionValues[storeData.affect[0]] ? storeData.conditionValues[storeData.affect[0]] : [];
                this.setState({
                    mainData: selectData
                });
            }
        }

        let oldData = storeData.data;
        let newData = [];

        console.log('GIS地图组件----newData=====', storeData);
        
        let lines = storeData.line ? storeData.line : [];
        let name = lines.length > 0 ? lines[0].task_id : '';
        this.setState({
            title: storeData.title,
            chartData: storeData.data,
            activeName: name,
            lines: lines,
            haveData: true,
        }, () => {
            this.drawMap();
        })
        // _this.drawMap();
    }
    


    // 绘制地图
    drawMap = () => {
        const _this = this;

        let mapId = 'chart_'+this.state.id+'_'+this.state.chartId;
        map = new AMap.Map(mapId, {
            mapStyle: 'https://amap://styles/darkblue',
            center: [104.06617,30.658426],
            // center: [116.397732, 39.912152],
            resizeEnable: true,
            zoom: 12,
        });

                //ControlBar 插件
        // map.plugin(["AMap.ControlBar"],function(){
        //     var controlBar = new AMap.ControlBar({
        //         theme:"dark"
        //     })
        //     map.addControl(controlBar)
        // });


        AMapUI.loadUI(['control/BasicControl'], function(BasicControl) {

            var zoomCtrl1 = new BasicControl.Zoom({
                    theme: 'dark'
                })

            map.addControl(zoomCtrl1);

        });
        
        //地图鹰眼插件
        map.plugin(["AMap.OverView"],function(){
            var view = new AMap.OverView();
            map.addControl(view);
        }); 

        //比例尺
        map.plugin(["AMap.Scale"],function(){
            var scale = new AMap.Scale();
            map.addControl(scale);   
        });

        //地图操作工具条插件
        // map.plugin(["AMap.ToolBar"],function(){
        //     //加载工具条
        //     var tool = new AMap.ToolBar();
        //     map.addControl(tool);    
        // });


        const lines =this.state.lines;
        const lines1=lines[0].lnglat
        const lines2=lines[0].predict_route
        const startImage=require('./images/start_blue.png')
        const startRedImage=require('./images/start_red.png')
        const endImage=require('./images/end_blue.png')
        const carImage=require('./images/map_truck.png')
        // 绘制轨迹
        if(lines1.length>0){
            let pathArr=[]
            // detail.carPath.map((item,index)=>{
            //     pathArr.push([item.longitude,item.latitude])
            // })
            var polyline = new AMap.Polyline({
                map: map,
                path: lines1,
                showDir:true,
                strokeColor: "#ef5350",  //线颜色
                // strokeOpacity: 1,     //线透明度
                strokeWeight: 6,      //线宽
                // strokeStyle: "solid"  //线样式
            });
            const markerPosition = [104.008325, 30.669995]

            // 添加点标记
            _this.addMarker(lines1[0],startRedImage);
            _this.addMarker(lines1[lines1.length-1],carImage);
            map.setFitView();
        }
        if(lines2){
            let pathArr=[]
            // detail.carPath.map((item,index)=>{
            //     pathArr.push([item.longitude,item.latitude])
            // })
            var polyline = new AMap.Polyline({
                map: map,
                path: lines2,
                showDir:true,
                strokeColor: "#42A5F5",  //线颜色
                // strokeOpacity: 1,     //线透明度
                strokeWeight: 6,      //线宽
                // strokeStyle: "solid"  //线样式
            });
            map.setFitView();
            _this.addMarker(lines2[0],startImage);
            _this.addMarker(lines2[lines2.length-1],endImage);
        }
        // layerLines = new Loca.LineLayer({
        //     map: map,
        // });
        
        // const markerPosition = [104.008325, 30.669995]

        // // 添加点标记
        // _this.addMarker(markerPosition);
        // 添加线路
        // _this.LineLayer();

        // 标注图层点击事件
        // map.on('click', _this.showInfoClick);
    }
    // 地图点击事件
    // showInfoClick = (e) => {
    //     // 改变全局变量
    //     // _this.onGlobalVariable();
    //     // 更新点标记
    //     this.addMarker();
    //     // 移除路线
    //     layerLines.setMap(null);
    // }
    // 添加点标记
    addMarker = (position,iconImage) => {
        const _this = this;
        // 删除点标记
        _this.removeMarkers();
        const markers=[];

        let markerData = _this.state.chartData;
        const marker = new AMap.Marker({
            icon: iconImage,
            position: position,
            anchor: 'center', //设置锚点
            offset: new AMap.Pixel(0,-21), //设置偏移量
            // label: {
            //     content: "<div class='labelContent' style='color: "+ color +";font-size: 16px;font-weight: 700'>"+item.name+"</div>",
            //     offset: new AMap.Pixel(-20, -18)
            // },
            clickable: true,
            // extData: item.name
        });
        map.add(marker);
        // map.add(markers);
    }
    // 删除点标记
    removeMarkers = () => {
        map.remove(markers);
    }
    // 添加线路
    LineLayer = (value) => {
        const _this = this;
        const lines=this.state.lines;
        // 移除
        layerLines.setMap(null);

        // console.log("")


        // 添加线路
        let layer = new Loca.LineLayer({
            map: map,
        });

        console.log('layer====value=====',value);
        let newLineData = [];
        lines.map((item,index) => {
            if (item.line_id == value) {
                newLineData.push(item);
            }
        })

        // // 绘制轨迹
        // if(lines[0].predict_route){
        //     let pathArr=[]
        //     // detail.carPath.map((item,index)=>{
        //     //     pathArr.push([item.longitude,item.latitude])
        //     // })
        //     var polyline = new AMap.Polyline({
        //         map: map,
        //         path: lines[0].predict_route,
        //         showDir:true,
        //         strokeColor: "#28F",  //线颜色
        //         // strokeOpacity: 1,     //线透明度
        //         strokeWeight: 6,      //线宽
        //         // strokeStyle: "solid"  //线样式
        //     });
        //     map.setFitView();

        // }


        console.log('_this.state.lines=====', _this.state.lines);
        layer.setData(_this.state.lines, {
            lnglat: 'lnglat'
        });
        layer.setOptions({
            style: {
                borderWidth: 5,
                opacity: 1,
                color: '#07E8E4',
            }
        });
        
        layer.render();
        // 添加至底图
        layer.setMap(map);
        layerLines = layer;
    }

    // 改变全局变量
    onGlobalVariable = (val) => {
        const { saveAffectId } = this.props.chartStore;
        saveAffectId(this.state.chartId);
        this.props.onGlobalVariable(val);
    }





    render() {
        const _this = this;
        const { endOpen } = _this.state;
        let Layer = this.props.layer;

        return (
            <div id={this.state.id+'_'+this.state.chartId} style={{padding:"30px 20px 20px 20px",zIndex: 9999,width: this.state.width,height: this.state.height,overflow: 'hidden'}}>
                <Layer width={this.state.width} title={this.state.title} chartId={this.state.chartId} choiceData={this.state.mainData}></Layer>
                <div className={styles.mapBox}  id={'chart_'+this.state.id+'_'+this.state.chartId} style={{height: '100%'}}></div>
                <div className="legend">
                  <div className="actualLine">
                      <div className="line"></div>
                  实际路线</div>
                  <div className="predictPath">
                      <div className="line"></div>
                  预估路线</div>
              </div>
            </div>

        )
    }


}
export default MarkerLineMap;

